$(function () {
	//基本信息
	let userId;
	let proveType;
	let loadingTip;
	// 下载引擎程序
	$('.engineDown').on('click', function () {
		window.location.href = 'https://doraemonkey.lanzouw.com/b03f2avyb'
	})
	$('.monitorDown').on('click', function () {
		$.ajax({
			url: window.monitorHttp + 'api/v1/monitor/download',
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				let data;
				try {
					data = JSON.parse(res)
				} catch (e) {
					layer.msg(e)
				}
				if (data.Code === 200) {
					window.location.href = data.Data;
				} else {
					layer.msg(data.Msg || '请求下载失败')
				}
			},
			error: function () {
				layer.msg('请求下载失败')
			}
		})
	})
	//改变界面展示
	function changeRenderHtml(data) {
		getUserLevelData().then(res=>{
			let userLevelArr=res;
			$("#userName").val(data.userName);
			$("#nickName").val(data.nickName);
			$("#phonenumber").val(data.phonenumber);
			$("#email").val(data.email);
			$('#remark').val(data.remark);
			$("#userInfo").removeClass("disabledNone");
			$("#accunt").text(data.nickName || data.userName);
			let userLevelName = userLevelArr.find(item => item.dictValue == data.level).dictLabel;
			$("#userLevelLabel").text(userLevelName);

			userId = data.userId;
			proveType = data.proveType;
			if (data.sex == "0") {
				$('input:radio:first').attr('checked', 'checked');
			} else {
				$('input:radio:last').attr('checked', 'checked');
			}
			if (data.proveType == 0) {
				$('#cer_Status').text('未认证(认证后可使用全部功能)');
			} else {
				$('#cer_Status').text('更改认证');
			}
			if (data.isGov == 1) {//特权标识
				$("#vipLable").removeClass("disabledNone");
			}
			certification(userId);
			if (data.loginDate) {
				$("#loginDate").html(data.loginDate.slice(0, 10));
			}
		});
	}
	var UserInfo = JSON.parse(sessionStorage.getItem('UserInfo'));
	changeRenderHtml(UserInfo);
	function getUserDataStats() {
		$.ajax({
			timeout: 30000,
			type: 'GET',
			url: window.Http + "/property/count/user/data",
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				if (res.code === 200) {
					console.log(res)
					$('#incomeNum').text(res.data.productNum);
					$('#paymentNum').text(res.data.productSize + ' GB');
					$('#rechargeNum').text(res.data.governNum);
					$('#giveNum').text(res.data.governSize + ' GB');
				} else {
					layer.msg("获取数据统计失败", { icon: 2 });
				}
			},
			error: function () {
				layer.msg('请求数据统计失败', { icon: 2 });
			}
		});
	}

	// 初始调用获取数据统计
	getUserDataStats();
	//获取用户信息
	function getUserInfo() {
		loadingTip = layer.load(1);
		$.ajax({
			timeout: 30000,
			type: 'GET',
			url: window.Http + "/getInfo",
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				layer.close(loadingTip);
				if (res.code == 200) {
					changeRenderHtml(res.user);
				} else if (res.code == 401) {
					layer.alert('未登录，请前往登录界面进行登录', {
						skin: 'layui-layer-lan'
						, closeBtn: 0
						, anim: 1 //动画类型
					}, function () {
						window.location.href = './login.html';
					});
					//alert("未登录，请前往登录界面进行登录")
				}
			}
		})
		//获取主权信息
		$.ajax({
			timeout: 30000,
			type: 'GET',
			url: window.Http + "/property/user/getDrInfo",
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				if (res.code == 200) {
					console.log('111',res)
					//changeRenderHtml(res.user);
				}
			}
		})

	}
	getUserInfo();
	// 认证信息
	// certification 函数，获取用户认证信息
	function certification(userId) {
		$.ajax({
			timeout: 30000,
			type: 'GET',
			url: window.Http + "/system/user/" + userId,
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success: function (res) {
				if (res.code == 200) {
					console.log(res);

					if (res.data.dataStatus === 1) {


						$("#upgradeSovereignty").click(function (e) {
							layer.msg("升级主权失败,您已经为主权账户", { icon: 2 });
						});
					} else {

						// 点击事件处理
						$("#upgradeSovereignty").click(function (e) {
							e.preventDefault();

							let data = {
								userName: $("#userName").val(),
								nickName: $("#nickName").val(),
								phonenumber: $("#phonenumber").val(),
								email: $("#email").val(),
								remark: $('#remark').val(),
								userId: userId,
								dataStatus: 1
							};

							$.ajax({
								timeout: 30000,
								type: 'PUT',
								url: window.Http + "/system/user",
								headers: {
									'Authorization': "Bearer " + sessionStorage.getItem('Token')
								},
								contentType: 'application/json',
								data: JSON.stringify(data),
								success: function (res) {
									console.log(res);
									if (res.code == 200) {
										layer.msg("升级主权成功", { icon: 1 });
										$('.zhuquan').html('您已经是主权账户').show();
									} else {
										layer.msg("升级主权失败,您已经为主权账户", { icon: 2 });
									}
								},
								error: function (xhr, textStatus, errorThrown) {
									console.error('AJAX Error:', textStatus, errorThrown);
									layer.msg("升级主权失败", { icon: 2 });
								}
							});
						});
					}

					// 处理用户认证信息显示
					if (res.data.proveType > 0) {
						$(".menuTab").find(".layui-this").siblings().removeClass("disabledNone");
						switch (res.data.proveType) {
							case 1:
								$('#cer_Change').html('个人');
								break;
							case 2:
								$('#cer_Change').html('私人企业');
								break;
							case 3:
								$('#cer_Change').html('国有企业');
								break;
							case 4:
								$('#cer_Change').html('事业单位');
								break;
							case 5:
								$('#cer_Change').html('政府部门');
								break;
							case 6:
								$('#cer_Change').html('社会组织');
								break;
							default:
								break;
						}
						$('#attestationa').find('a').html('已通过');
						$("#auditTime").html(res.data.createTime);
						$("#loginDate").html(res.data.loginDate ? res.data.loginDate.slice(0, 10) : "—");
					} else {
						switch (res.authInfo.proveType) {
							case 1:
								$('#cer_Change').html('个人');
								break;
							case 2:
								$('#cer_Change').html('私人企业');
								break;
							case 3:
								$('#cer_Change').html('国有重点企业');
								break;
							case 4:
								$('#cer_Change').html('组织机构');
								break;
							case 5:
								$('#cer_Change').html('事业单位');
								break;
							case 6:
								$('#cer_Change').html('普通居委会');
								break;
							case 7:
								$('#cer_Change').html('权力机构');
								break;
							default:
								break;
						}
						switch (res.authInfo.auditStatus) {
							case 0:
								$('#attestationa').find('a').html('待审核');
								break;
							case 1:
								$('#attestationa').find('a').html('已通过');
								break;
							case -1:
								$('#attestationa').find('a').html('已驳回');
								$('#reasonMsg').removeClass("disabledNone");
								$('#reasonMsg').html(res.data.auditResult);
								break;
							default:
								break;
						}
						$("#auditTime").html(res.data.createTime);
						$("#loginDate").html(res.data ? res.data.loginDate.slice(0, 10) : "—");
					}

				} else {
					layer.msg(res.msg);
					$('#attestationa').find('a').html('未认证');
					$('#cer_Change').html('未认证');
					$("#auditTime").html('未认证');
					$("#loginDate").html(res.data ? res.data.loginDate.slice(0, 10) : "—");
				}
			},
			error: function (xhr, textStatus, errorThrown) {
				console.error('AJAX Error:', textStatus, errorThrown);
			}
		});
	}

	$("#cer_Status").click(function () {
		// 认证时需要传参reProve 1：新认证 2：重新认证
		if ($('#cer_Status').text() == '更改认证') {
			window.sessionStorage.setItem('reProve', 2)
		} else {
			window.sessionStorage.setItem('reProve', 1)
		}
		window.location.href = './authentication.html';
	})

	//
	let infoList
	$("#editBtn").click(function () {
		$(this).addClass("disabledNone");
		$(".Btn").removeClass("disabledNone");
		$("input").attr("disabled", false);
		$("textarea").attr("disabled", false);
		$(".regular input").attr("disabled", true);
		infoList = {
			userName: $("#userName").val(),
			nickName: $("#nickName").val(),
			phonenumber: $("#phonenumber").val(),
			email: $("#email").val(),
			remark: $('#remark').val(),
		}
		check()
	})
	// 个人信息修改验证
	function check() {
		var regnickn = /^[\u4E00-\u9FA5A-Za-z]{2,10}$/  //别名
		var regemailn = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/  //邮箱
		let regtel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/ //电话号码
		var nickn = $('#nickName');
		var emailn = $('#email');
		var tel = $('#phonenumber');
		regexp(nickn, regnickn, '请输入2-10位别名');
		regexp(emailn, regemailn, '请正确输入邮箱');
		regexp(tel, regtel, '请正确输入电话号码');
		// 表单验证的函数
		function regexp(ele, reg, str) {
			$(ele).blur(function () {
				if (!reg.test(this.value)) {
					this.nextElementSibling.className = 'err';
					this.nextElementSibling.innerHTML = str;
					$(".submitBtn").attr('disabled', true)
				} else {
					this.nextElementSibling.className = 'success';
					$(".submitBtn").attr('disabled', false)
				}
			})
		};
	}

	// $("#upgradeSovereignty").click(function (e) {
	// 	e.preventDefault();
	// 	let data = {
	// 		userName: $("#userName").val(),
	// 		nickName: $("#nickName").val(),
	// 		phonenumber: $("#phonenumber").val(),
	// 		email: $("#email").val(),
	// 		remark: $('#remark').val(),
	// 		userId: userId,
	// 		dataStatus:1
	// 	}
	// 	$.ajax({
	// 		timeout: 30000,
	// 		type: 'PUT',
	// 		url: window.Http + "/system/user",
	// 		headers: {
	// 			'Authorization': "Bearer " + sessionStorage.getItem('Token')
	// 		},
	// 		contentType: 'application/json',
	// 		data: JSON.stringify(data),
	// 		success: function (res) {
	// 			console.log(res);
	// 			if (res.code == 200) {
	// 				layer.msg("升级主权成功", { icon: 1 });
	// 			} else {
	// 				layer.msg("升级主权失败,您已经为主权账户", { icon: 2 });
	// 			}
	// 		}
	// 	})
	// })
	$(".submitBtn").click(function (e) {
		e.preventDefault();
		$("#editBtn").removeClass("disabledNone");
		$("input").attr("disabled", true);
		$("textarea").attr("disabled", true);
		$(this).parent('.Btn').addClass("disabledNone");

		let data = {
			userName: $("#userName").val(),
			nickName: $("#nickName").val(),
			phonenumber: $("#phonenumber").val(),
			email: $("#email").val(),
			remark: $('#remark').val(),
			userId: userId
		}
		$.ajax({
			timeout: 30000,
			type: 'PUT',
			url: window.Http + "/system/user",
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			contentType: 'application/json',
			data: JSON.stringify(data),
			success: function (res) {
				if (res.code == 200) {
					layer.msg("修改成功", { icon: 1 });
					getUserInfo();
				} else {
					layer.msg("修改异常", { icon: 2 });
				}
			}
		})
	})
	$('#closeEditBtn').click(function (e) {
		e.preventDefault()
		$("#editBtn").removeClass("disabledNone");
		$("input").attr("disabled", true);
		$("textarea").attr("disabled", true);
		$(this).parents('form').find('span').each(function (index, val) {
			$(val)[0].className = 'success'
		})
		$(this).parent('.Btn').addClass("disabledNone");
		$("#userName").val(infoList.userName)
		$("#nickName").val(infoList.nickName)
		$("#phonenumber").val(infoList.phonenumber)
		$("#email").val(infoList.email)
		$('#remark').val(infoList.remark)
	})
	//退出登录
	$('#logOutBtn').click(function (e) {
		e.preventDefault()
		layer.confirm('是否确认退出当前登录账号?', { icon: 3, title: '提示' }, function (index) {
			//请求退出登录接口
			$.ajax({
				timeout: 30000,
				url: window.Http + "/logout",
				type: 'POST',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code == 200) {
						layer.msg("退出成功", { icon: 1 });
						sessionStorage.setItem('Token', "");
						sessionStorage.setItem('UserId', "");
						setTimeout(function () {
							window.location.href = './login.html';
						}, 1500)
					} else {
						layer.msg(res.msg);
					}
				}
			})
			layer.close(loadingTip);
		});
	})
	function getUserLevelData() {
		return new Promise(function (resolve, reject) {
			$.ajax({
				timeout: 30000,
				url: window.Http + "/system/dict/data/getDictList",
				type: 'GET',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data: {
					dictType: 'user_level'
				},
				success: function (res) {
					if (res.code === 200) {
						resolve(res.data)
					}else {
						reject(res.msg)
					}
				}
			})
		})
	}
})
